package com.kucowka.struts.messages;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kucowka.struts.actions.chat.history.HistorySaverImpl;
import com.kucowka.struts.actions.chat.history.HistorySaverTimerTask;
import com.kucowka.struts.actions.chat.history.StringSaver;

public class MessageStore {

	private static final Logger logger = LoggerFactory
			.getLogger(MessageStore.class);

	private static final long DELAY = 5000;

	private static Map<String, Message> messages = new HashMap<String, Message>();
	private static Map<String, List<String>> authorsMessagesForDispaly = new HashMap<String, List<String>>();
	private static Timer timer;

	static {
		timer = new Timer();
		HistorySaverTimerTask hstt = new HistorySaverTimerTask();
		StringSaver ss;

		try {
			ss = new StringSaver(new PrintWriter(new FileWriter(new File(
					"/home/robert/messages.txt"))));
			hstt.setHistorySaver(new HistorySaverImpl(ss));
			timer.schedule(hstt, new Date(), DELAY);
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("IOException while creating PrintWriter");
		}
	}

	public static synchronized void addMessage(String author, String content) {
		String uuid = UUID.randomUUID().toString();
		for (Map.Entry<String, List<String>> entry : authorsMessagesForDispaly
				.entrySet()) {
			entry.getValue().add(uuid);
		}
		messages.put(uuid, new Message(content, author));
	}

	public static synchronized void addAuthor(String sessionId) {
		authorsMessagesForDispaly.put(sessionId, new LinkedList<String>());
	}

	public static synchronized List<Message> getMessages(String sessionId) {
		LinkedList<Message> messagesList = new LinkedList<Message>();
		for (String uuid : authorsMessagesForDispaly.get(sessionId)) {
			messagesList.addFirst(messages.get(uuid));
		}
		authorsMessagesForDispaly.get(sessionId).clear();
		return messagesList;
	}

	public static Map<String, Message> getMessages() {
		return new HashMap<String, Message>(messages);
	}
}
